var ExcelForm = function () {
  var template = /* html */ `
    <div class="excel-form" v-loading.fullscreen.lock="loading">
      <div class="excel-form-file">
        <input :key="id" v-if="!loading" ref="uploadInput" type="file" @change="importExcel">
      </div>
      <div class="excel-form-handle">
        <el-button size="medium" type="primary" @click="loadTemplate">下载Excel模板</el-button>
        <el-button size="medium" type="primary" @click="uploadExcel">上传Excel</el-button>
        <el-button v-if="warnList!==null" size="medium" type="primary" @click="save">导入数据</el-button>
      </div>
      <div class="excel-form-table-div">
        <el-table v-if="warnList!==null" fit border :data="warnList" style="width: 100%" height="parent">
          <el-table-column type="index" label="行号" width="50" align="center"></el-table-column>
          <el-table-column label="警报类型" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <table-input size="small" v-model="scope.row.typeName"></table-input>
            </template>
          </el-table-column>
          <el-table-column label="警报代码" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <table-input size="small" v-model="scope.row.alarmCode"></table-input>
            </template>
          </el-table-column>
          <el-table-column label="警报描述" min-width="150px" header-align="center">
            <template slot-scope="scope">
              <table-input size="small" v-model="scope.row.codeDescribe"></table-input>
            </template>
          </el-table-column>
          <el-table-column label="看板是否显示" min-width="150px" align="center">
            <template slot-scope="scope">
              <span>{{i18n.getMsg('machineRepair.warnSetting.isShow.'+scope.row.isShow)}}</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-else class="no-data">
          点击“上传Excel”按钮，上传需要导入的数据
        </div>
      </div>
    </div>
  `;

  return {
    data: function () {
      return {
        loading: false,
        id: SysUtil.getId(),
        warnList: null,
        isShowList: i18n.getDropDown('machineRepair.warnSetting.isShow', [1, 2])
      };
    },

    methods: {
      loadTemplate: function () {
        window.open("./template/警报设置模板.xls");
      },

      uploadExcel: function () {
        this.$refs['uploadInput'].click();
      },

      importExcel: function () {
        var file = this.$refs['uploadInput'].files[0];
        this.resetFileId();

        var name = file.name;
        if (!name.endsWith('.xls') && !name.endsWith('.xlsx')) {
          this.$alert('请上传.xls或.xlsx为后缀的excel文件', '信息');
          return;
        }

        this.loading = true;
        var self = this;
        this.$nextTick(function () {
          import_excel_to_json(file, {
            startCell: 'A3',
            formatOption: {
              "警报代码": "alarmCode",
              "警报类型": "typeName",
              "警报描述": "codeDescribe",
              "看板是否显示": "isShow"
            }
          }).then(function (warnList) {
            if (warnList.length === 0) {
              self.$alert('excel文件里没有警报数据', '信息');
              self.warnList = null;
            } else {
              warnList = _.orderBy(warnList, ['typeName', function (warn) {
                var alarmCode = warn.alarmCode;
                var code = parseInt(alarmCode);
                if (isNaN(code)) {
                  return alarmCode;
                }
                return code;
              }], ['asc', 'asc']);
              warnList = _.map(warnList, function (warn, index) {
                var isShow = warn.isShow;
                if (SysUtil.isEmpty(isShow)) {
                  isShow = 1;
                } else {
                  isShow = i18n.getKeyByValue('machineRepair.warnSetting.isShow', isShow);
                  isShow = Number(isShow);
                }
                warn.isShow = isShow;
                warn = new WarnFormModel(warn);
                warn.rowIndex = index + 1;
                return warn;
              });
              console.log('warnList', warnList);
              self.warnList = warnList;
            }
            self.loading = false;
          }).catch(function () {
            self.loading = false;
          });
        });
      },

      save: function () {
        var warnList = this.warnList;
        if (SysUtil.isEmpty(warnList)) {
          this.$alert('没有数据可以导入', '信息');
          return;
        }

        var warns = [];
        for (var i = 0; i < warnList.length; i++) {
          var warn = warnList[i];
          var code = warn.checkValid();
          if (code !== '') {
            var msg = i18n.getMsg(`machineRepair.warnSetting.field.${code}`);
            this.$alert(`第${i+1}行${msg}，请修改相应行数据`, '信息');
            return;
          }
          var postData = warn.getObject();
          warns.push(postData);
        }

        var data = _.uniqBy(warnList, function (warn) {
          return `${warn.typeName}$#$${warn.alarmCode}`;
        });
        if (warnList.length !== data.length) {
          var sameList = _.difference(warnList, data);
          var obj = sameList[0];
          sameList = _.filter(warnList, {
            typeName: obj.typeName,
            alarmCode: obj.alarmCode
          });
          var indexList = _.map(sameList, 'rowIndex');
          this.$alert(`第${indexList}行的警报类型和警报代码完全相同`, '信息');
          return;
        }
        this.toSave(warns);
      },

      toSave: function (warns) {
        this.loading = true;
        var self = this;
        ajaxRequest('equipment/addEquipmentAlarmCode', {
          jsonArray: JSON.stringify(warns)
        }).then(function () {
          self.loading = false;
          self.$alert('警报数据成功导入', '信息', {
            callback: function () {
              self.$emit('import-success', warns);
            }
          });
        }).catch(function () {
          self.loading = false;
        });
      },

      resetFileId: function () {
        this.id = SysUtil.getId();
      }
    },

    components: {
      TableInput: TableInput
    },

    template: template
  };
}();
